// pages/volunteer/activity-detail.js
Page({
  data: {
    activityId: '',
    activity: {},
    isLiked: false,
    isSignedUp: false,
    showCommentModal: false,
    showConsultationModal: false,
    commentContent: '',
    comments: [],
    
    // 默认数据
    guarantees: [
      { id: 1, icon: '🛡️', text: '活动保险' },
      { id: 2, icon: '🍽️', text: '餐饮保障' },
      { id: 3, icon: '🚌', text: '交通保障' },
      { id: 4, icon: '👕', text: '服装装备' },
      { id: 5, icon: '📋', text: '培训指导' },
      { id: 6, icon: '🏆', text: '荣誉证书' }
    ],
    
    volunteers: [
      { id: 1, name: '张小明', avatar: '/images/avatar1.jpg' },
      { id: 2, name: '李小红', avatar: '/images/avatar2.jpg' },
      { id: 3, name: '王小华', avatar: '/images/avatar3.jpg' },
      { id: 4, name: '赵小丽', avatar: '/images/avatar4.jpg' },
      { id: 5, name: '刘小强', avatar: '/images/avatar5.jpg' }
    ],
    
    defaultDetails: '这是一个非常有意义的志愿者活动，旨在通过实际行动改善社区环境，提升居民生活质量。活动将组织志愿者清理城区公厕和小区内的非法小广告，为城市环境美化贡献力量。\n\n活动内容包括：\n1. 清理公厕周边环境\n2. 清除小区内非法小广告\n3. 宣传环保理念\n4. 记录活动过程\n\n参与要求：\n- 年满18周岁\n- 身体健康\n- 有责任心\n- 能够按时参加活动\n\n活动时间：2024年8月26日 上午9:00-12:00\n集合地点：界首市人民广场\n\n请携带：\n- 身份证\n- 舒适服装\n- 饮用水\n- 防晒用品'
  },

  onLoad: function (options) {
    console.log('活动详情页面加载，参数:', options);
    
    if (options.id) {
      this.setData({
        activityId: options.id
      });
      this.loadActivityDetail(options.id);
    } else {
      // 如果没有传入ID，使用默认数据
      this.loadActivityDetail('1');
    }
  },

  onShow: function () {
    this.loadUserStatus();
    this.loadComments();
  },

  // 加载活动详情
  loadActivityDetail: function (id) {
    console.log('加载活动详情，ID:', id);
    
    // 模拟从服务器获取活动数据
    const activityData = {
      '1': {
        id: '1',
        title: '8.24小小志愿者选拔志愿服务',
        organization: '阜阳市城市规划展示馆',
        image: '/images/1.jpg',
        participants: 0,
        maxParticipants: 5,
        distance: '>50km',
        district: '颍州区',
        status: 'recruiting',
        statusText: '招募中',
        serviceType: 'education',
        serviceTypeText: '教育服务',
        targetAudience: '儿童青少年',
        location: '阜阳市城市规划展示馆',
        date: '2024-08-24',
        time: '09:00-12:00',
        organizerAvatar: '/images/organizer1.jpg',
        rating: 4.8,
        ratingCount: 156,
        reminder: '请携带身份证，穿着舒适服装，准时到达集合地点。活动期间请遵守秩序，注意安全。',
        details: '这是一个专门为儿童设计的志愿者选拔活动，通过互动游戏和实践活动，培养孩子们的志愿服务意识和团队合作精神。活动将包括参观展览、互动体验、志愿服务培训等环节。'
      },
      '2': {
        id: '2',
        title: '敬老润我心,服务献爱心',
        organization: '颍东区三助志愿者服务队',
        image: '/images/1.jpg',
        participants: 13,
        maxParticipants: 20,
        distance: '>50km',
        district: '颍东区',
        status: 'recruiting',
        statusText: '招募中',
        serviceType: 'elderly',
        serviceTypeText: '敬老服务',
        targetAudience: '老年人',
        location: '颍东区敬老院',
        date: '2024-08-25',
        time: '14:00-17:00',
        organizerAvatar: '/images/organizer2.jpg',
        rating: 4.9,
        ratingCount: 203,
        reminder: '请携带身份证，穿着得体服装。活动期间请保持安静，尊重老人，注意言行举止。',
        details: '为敬老院的老人提供陪伴服务，包括聊天、按摩、唱歌、游戏等活动，让老人感受到社会的关爱和温暖。'
      },
      '3': {
        id: '3',
        title: '"清厕焕新"清除城区公厕、小区非法小广告公益行动',
        organization: '界首市阳帆志愿者协会',
        image: '/images/1.jpg',
        participants: 7,
        maxParticipants: 200,
        distance: '>50km',
        district: '界首市',
        status: 'recruiting',
        statusText: '招募中',
        serviceType: 'environment',
        serviceTypeText: '环保服务',
        targetAudience: '社区居民',
        location: '界首市城区各公厕及小区',
        date: '2024-08-26',
        time: '08:00-12:00',
        organizerAvatar: '/images/organizer3.jpg',
        rating: 4.7,
        ratingCount: 89,
        reminder: '请携带身份证，穿着舒适服装，准备清洁工具。活动期间注意安全，遵守交通规则。',
        details: '组织志愿者清理城区公厕和小区内的非法小广告，美化城市环境，提升居民生活质量。活动将分组进行，每个小组负责指定区域。'
      }
    };

    const activity = activityData[id] || activityData['1'];
    
    this.setData({
      activity: activity
    });
    
    console.log('活动数据加载完成:', activity);
  },

  // 加载用户状态
  loadUserStatus: function () {
    const userActivities = wx.getStorageSync('userActivities') || [];
    const userLikes = wx.getStorageSync('userLikes') || [];
    
    const isSignedUp = userActivities.some(ua => ua.activityId === this.data.activityId);
    const isLiked = userLikes.includes(this.data.activityId);
    
    this.setData({ 
      isSignedUp, 
      isLiked 
    });
    
    console.log('用户状态加载完成:', { isSignedUp, isLiked });
  },

  // 加载评论
  loadComments: function () {
    const comments = wx.getStorageSync(`activity_comments_${this.data.activityId}`) || [];
    this.setData({ comments });
    console.log('评论加载完成:', comments);
  },

  // 返回上一页
  goBack: function () {
    wx.navigateBack();
  },

  // 切换点赞状态
  toggleLike: function () {
    const userLikes = wx.getStorageSync('userLikes') || [];
    const activityId = this.data.activityId;
    
    if (this.data.isLiked) {
      // 取消点赞
      const newLikes = userLikes.filter(id => id !== activityId);
      wx.setStorageSync('userLikes', newLikes);
      this.setData({ isLiked: false });
      wx.showToast({
        title: '已取消点赞',
        icon: 'success'
      });
    } else {
      // 添加点赞
      userLikes.push(activityId);
      wx.setStorageSync('userLikes', userLikes);
      this.setData({ isLiked: true });
      wx.showToast({
        title: '点赞成功',
        icon: 'success'
      });
    }
  },

  // 分享活动
  shareActivity: function () {
    wx.showActionSheet({
      itemList: ['分享给朋友', '分享到朋友圈', '复制链接'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            wx.showToast({
              title: '请点击右上角分享',
              icon: 'none'
            });
            break;
          case 1:
            wx.showToast({
              title: '请点击右上角分享',
              icon: 'none'
            });
            break;
          case 2:
            wx.setClipboardData({
              data: `活动详情：${this.data.activity.title}`,
              success: () => {
                wx.showToast({
                  title: '链接已复制',
                  icon: 'success'
                });
              }
            });
            break;
        }
      }
    });
  },

  // 查看组织方详情
  viewOrganizerDetail: function () {
    wx.showToast({
      title: '组织方详情功能开发中',
      icon: 'none'
    });
  },

  // 查看所有志愿者
  viewAllVolunteers: function () {
    wx.showModal({
      title: '已报名志愿者',
      content: `共有${this.data.volunteers.length}人报名参加此活动`,
      showCancel: false
    });
  },

  // 显示留言输入
  showCommentInput: function () {
    this.setData({
      showCommentModal: true
    });
  },

  // 关闭留言弹窗
  closeCommentModal: function () {
    this.setData({
      showCommentModal: false,
      commentContent: ''
    });
  },

  // 留言输入
  onCommentInput: function (e) {
    this.setData({
      commentContent: e.detail.value
    });
  },

  // 提交留言
  submitComment: function () {
    if (!this.data.commentContent.trim()) {
      wx.showToast({
        title: '请输入留言内容',
        icon: 'none'
      });
      return;
    }

    const newComment = {
      id: Date.now(),
      author: '我',
      content: this.data.commentContent,
      time: new Date().toLocaleString()
    };

    const comments = [newComment, ...this.data.comments];
    
    // 保存到本地存储
    wx.setStorageSync(`activity_comments_${this.data.activityId}`, comments);
    
    this.setData({
      comments,
      showCommentModal: false,
      commentContent: ''
    });

    wx.showToast({
      title: '留言发表成功',
      icon: 'success'
    });
  },

  // 显示咨询弹窗
  showConsultation: function () {
    this.setData({
      showConsultationModal: true
    });
  },

  // 关闭咨询弹窗
  closeConsultationModal: function () {
    this.setData({
      showConsultationModal: false
    });
  },

  // 拨打电话
  callOrganizer: function () {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567',
      success: () => {
        console.log('拨打电话成功');
      },
      fail: () => {
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  },

  // 添加微信
  addWeChat: function () {
    wx.setClipboardData({
      data: 'volunteer_wechat_123',
      success: () => {
        wx.showToast({
          title: '微信号已复制',
          icon: 'success'
        });
      }
    });
  },

  // 查看常见问题
  viewFAQ: function () {
    wx.showModal({
      title: '常见问题',
      content: '1. 如何报名参加活动？\n点击"立即报名"按钮即可报名。\n\n2. 活动需要准备什么？\n请查看活动详情中的要求。\n\n3. 可以取消报名吗？\n活动开始前24小时可以取消。',
      showCancel: false
    });
  },

  // 报名活动
  signupActivity: function () {
    if (this.data.isSignedUp) {
      wx.showModal({
        title: '已报名',
        content: '您已经报名参加此活动，如需取消请前往"我的活动"页面操作。',
        showCancel: false
      });
      return;
    }

    // 检查是否还有名额
    if (this.data.activity.participants >= this.data.activity.maxParticipants) {
      wx.showToast({
        title: '活动已满员',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认报名',
      content: `确定要报名参加"${this.data.activity.title}"吗？`,
      confirmText: '确定报名',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.submitSignup();
        }
      }
    });
  },

  // 提交报名
  submitSignup: function () {
    wx.showLoading({
      title: '报名中...'
    });

    setTimeout(() => {
      // 保存用户活动记录
      const userActivities = wx.getStorageSync('userActivities') || [];
      const newUserActivity = {
        activityId: this.data.activityId,
        activityTitle: this.data.activity.title,
        joinTime: new Date().toISOString(),
        status: 'registered'
      };
      
      userActivities.push(newUserActivity);
      wx.setStorageSync('userActivities', userActivities);

      // 更新活动参与人数
      const activity = { ...this.data.activity };
      activity.participants += 1;
      
      this.setData({
        activity,
        isSignedUp: true
      });

      wx.hideLoading();
      wx.showToast({
        title: '报名成功！',
        icon: 'success'
      });
    }, 1000);
  },

  // 分享给朋友
  onShareAppMessage: function () {
    return {
      title: this.data.activity.title,
      path: `/pages/volunteer/activity-detail?id=${this.data.activityId}`,
      imageUrl: this.data.activity.image
    };
  },

  // 分享到朋友圈
  onShareTimeline: function () {
    return {
      title: this.data.activity.title,
      imageUrl: this.data.activity.image
    };
  }
});
